<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Operation\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Carbon\Carbon;
use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsClass;
use Laminas\Mvc\I18n\Translator;
use Operation\Entity\Coupon;
use Operation\Entity\UserCoupon;
use Operation\Form\CouponForm;
use Operation\Form\SearchUserCouponForm;
use Operation\Service\CouponManager;
use Operation\Service\UserCouponManager;

/**
 * 优惠券
 * Class CouponController
 * @package Operation\Controller
 */
class CouponController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $couponManager;
    private $userCouponManager;

    private $couponGetType;
    private $userCouponStateArray;

    public function __construct(
        Translator $translator,
        EntityManager $entityManager,
        CouponManager $couponManager,
        UserCouponManager $userCouponManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->couponManager    = $couponManager;
        $this->userCouponManager= $userCouponManager;

        $this->couponGetType = [
            'buy'   => $this->translator->translate('购物直接获取'),
            'click' => $this->translator->translate('点击直接获取(登录用户)'),
            'register' => $this->translator->translate('注册获取')
        ];
        $this->userCouponStateArray = [
            0 => $this->translator->translate('未生效'),
            1 => $this->translator->translate('可用'),
            2 => $this->translator->translate('已用'),
            3 => $this->translator->translate('已过期'),
        ];
    }

    /**
     * 优惠券列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $couponList = $this->entityManager->getRepository(Coupon::class)->findCouponList();
        return ['couponList' => $couponList, 'couponGetType' => $this->couponGetType];
    }

    /**
     * 添加优惠券
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        //商品分类
        $goodsClass = $this->entityManager->getRepository(GoodsClass::class)->findBy([], ['classTopId' => 'ASC', 'classSort' => 'ASC']);
        $classList  = Common::classOptions($goodsClass);
        //商品品牌
        $brandList  = $this->goodsPlugin()->goodsBrandOptions('', false);

        $form = new CouponForm();
        $form->get('getCouponType')->setValueOptions($this->couponGetType);
        $form->get('getUserType')->setValueOptions(['allUser' => $this->translator->translate('所有客户'), 'userGroup' => $this->translator->translate('客户分组')]);
        $form->get('userGroup')->setValueOptions($this->userPlugin()->userGroupOptions('', false));
        $form->get('getGoodsType')->setValueOptions(['allGoods' => $this->translator->translate('所有商品'), 'goodsClass' => $this->translator->translate('商品分类'), 'goodsBrand' => $this->translator->translate('商品品牌')]);
        $form->get('goodsBrand')->setValueOptions($brandList);
        $form->get('goodsClass')->setValueOptions($this->goodsPlugin()->classValueArray($goodsClass));

        if($this->getRequest()->isPost()) {
            $postData = $this->params()->fromPost();
            $form->setData($postData);
            if ($form->isValid()) {
                $data = $form->getData();

                if(!empty($data['couponStartTime']))    $data['couponStartTime']    = Carbon::parse($data['couponStartTime'])->timestamp;
                if(!empty($data['couponEndTime']))      $data['couponEndTime']      = Carbon::parse($data['couponEndTime'].' 23:59:59')->timestamp;
                if(!empty($data['getCouponStartTime'])) $data['getCouponStartTime'] = Carbon::parse($data['getCouponStartTime'])->timestamp;
                if(!empty($data['getCouponEndTime']))   $data['getCouponEndTime']   = Carbon::parse($data['getCouponEndTime'].' 23:59:59')->timestamp;

                $data['getUserGroup']  = serialize((!in_array($data['getUserType'], ['allUser']) ? $data[$data['getUserType']] : []));
                $data['getGoodsBody']  = serialize((!in_array($data['getGoodsType'], ['allGoods']) ? $data[$data['getGoodsType']] : []));

                $couponInfo = $this->couponManager->addCoupon($data);
                $this->createConfig()->createCoupon();

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('优惠券 %s 添加成功!'), $couponInfo->getCouponTitle()), $this->translator->translate('优惠券'));

                return $this->redirect()->toRoute('operation-coupon');
            }
        }

        return [
            'form' => $form,
            'classList' => $classList,
            'brandList' => $brandList,
            'currencySymbol'=> Common::configValue('default', 'currency')['symbol']
        ];
    }

    /**
     * 优惠券编辑
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAction()
    {
        $couponId = (int) $this->params()->fromRoute('id', -1);
        $couponInfo = $this->entityManager->getRepository(Coupon::class)->findOneBy(['couponId' => $couponId]);
        if ($couponInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该优惠券不存在!'));
            return $this->redirect()->toRoute('operation-coupon');
        }

        //商品分类
        $goodsClass = $this->entityManager->getRepository(GoodsClass::class)->findBy([], ['classTopId' => 'ASC', 'classSort' => 'ASC']);
        $classList  = Common::classOptions($goodsClass);
        //商品品牌
        $brandList  = $this->goodsPlugin()->goodsBrandOptions('', false);

        $form = new CouponForm();
        $form->get('getCouponType')->setValueOptions($this->couponGetType);
        $form->get('getUserType')->setValueOptions(['allUser' => $this->translator->translate('所有客户'), 'userGroup' => $this->translator->translate('客户分组')]);
        $form->get('userGroup')->setValueOptions($this->userPlugin()->userGroupOptions('', false));
        $form->get('getGoodsType')->setValueOptions(['allGoods' => $this->translator->translate('所有商品'), 'goodsClass' => $this->translator->translate('商品分类'), 'goodsBrand' => $this->translator->translate('商品品牌')]);
        $form->get('goodsBrand')->setValueOptions($brandList);
        $form->get('goodsClass')->setValueOptions($this->goodsPlugin()->classValueArray($goodsClass));

        if ($this->getRequest()->isPost()) {
            $postData = $this->params()->fromPost();
            $form->setData($postData);
            if ($form->isValid()) {
                $data = $form->getData();

                if(!empty($data['couponStartTime']))    $data['couponStartTime']    = Carbon::parse($data['couponStartTime'])->timestamp;
                if(!empty($data['couponEndTime']))      $data['couponEndTime']      = Carbon::parse($data['couponEndTime'].' 23:59:59')->timestamp;
                if(!empty($data['getCouponStartTime'])) $data['getCouponStartTime'] = Carbon::parse($data['getCouponStartTime'])->timestamp;
                if(!empty($data['getCouponEndTime']))   $data['getCouponEndTime']   = Carbon::parse($data['getCouponEndTime'].' 23:59:59')->timestamp;

                $data['getUserGroup']  = serialize((!in_array($data['getUserType'], ['allUser']) ? $data[$data['getUserType']] : []));
                $data['getGoodsBody']  = serialize((!in_array($data['getGoodsType'], ['allGoods']) ? $data[$data['getGoodsType']] : []));

                $couponInfo = $this->couponManager->editCoupon($data, $couponInfo);
                $this->createConfig()->createCoupon();

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('优惠券 %s 编辑成功!'), $couponInfo->getCouponTitle()), $this->translator->translate('优惠券'));

                return $this->redirect()->toRoute('operation-coupon');
            }
        } else {
            $couponArray = $couponInfo->valuesArray();
            $couponArray['couponStartTime']     = $couponArray['couponStartTime'] > 0       ? date("Y-m-d", $couponArray['couponStartTime'])    : '';
            $couponArray['couponEndTime']       = $couponArray['couponEndTime'] > 0         ? date("Y-m-d", $couponArray['couponEndTime'])      : '';
            $couponArray['getCouponStartTime']  = $couponArray['getCouponStartTime'] > 0    ? date("Y-m-d", $couponArray['getCouponStartTime']) : '';
            $couponArray['getCouponEndTime']    = $couponArray['getCouponEndTime'] > 0      ? date("Y-m-d", $couponArray['getCouponEndTime'])   : '';
            $form->setData($couponArray);
            if($couponArray['getUserType'] == 'userGroup') {
                $form->setData(['userGroup' => unserialize($couponArray['getUserGroup'])]);
            }
        }

        return [
            'form' => $form,
            'classList' => $classList,
            'brandList' => $brandList,
            'couponInfo'=> $couponInfo,
            'currencySymbol'=> Common::configValue('default', 'currency')['symbol']
        ];
    }

    /**
     * 会员获取的优惠券
     * @return array|\Laminas\Http\Response
     */
    public function userCouponListAction()
    {
        $couponId = (int) $this->params()->fromRoute('id', -1);
        $couponInfo = $this->entityManager->getRepository(Coupon::class)->findOneBy(['couponId' => $couponId]);
        if ($couponInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该优惠券不存在!'));
            return $this->redirect()->toRoute('operation-coupon');
        }

        $page = (int) $this->params()->fromQuery('page', 1);

        $search = [];
        $searchForm = new SearchUserCouponForm($couponInfo);
        $searchForm->get('coupon_use_state')->setValueOptions($this->userCouponStateArray);
        if($this->getRequest()->isGet()) {
            $data = $this->params()->fromQuery();
            $searchForm->setData($data);
            if($searchForm->isValid()) $search = $searchForm->getData();
        }

        $query      = $this->entityManager->getRepository(UserCoupon::class)->findUserCouponList($couponId, $search);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return [
            'searchForm'        => $searchForm,
            'couponInfo'        => $couponInfo,
            'userCouponList'    => $paginator,
            'userCouponStateArray' => $this->userCouponStateArray
        ];
    }

    /**
     * 优惠券删除
     * @return mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $couponId = (int) $this->params()->fromRoute('id', -1);
        $couponInfo = $this->entityManager->getRepository(Coupon::class)->findOneBy(['couponId' => $couponId]);
        if ($couponInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该优惠券不存在!'));
            return $this->adminCommon()->toReferer();
        }

        $this->couponManager->deleteCoupon($couponInfo);
        $this->userCouponManager->deleteUserCoupon($couponId);
        $this->createConfig()->createCoupon();

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('优惠券 %s 删除成功!'), $couponInfo->getCouponTitle()), $this->translator->translate('优惠券'));

        return $this->adminCommon()->toReferer();
    }
}